package com.itobase.questionnaire.controller;

import com.itobase.questionnaire.VO.PageDatas;
import com.itobase.questionnaire.model.SendPool;
import com.itobase.questionnaire.model.Survey;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.SendRepository;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.repository.UserRepository;
import com.itobase.questionnaire.service.impl.UrlService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.util.ListUtil;
import com.itobase.questionnaire.util.Message;
import com.itobase.questionnaire.util.PagingUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author liucong
 * @date 2018/8/6
 */



@RestController
@RequestMapping("url")
public class UrlController {


    @Autowired
    UrlService urlService;

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    SendRepository sendRepository;

    static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private Logger logger = LoggerFactory.getLogger(getClass());


    //增加人员到短信池中
    @PostMapping("addPool")
    public Message insert(@RequestBody Map<String, Object> map){
        String id = (String) map.get("id");
        Survey survey = surveyRepository.findById(id);
        if (survey == null) {
            return Message.createSuc("调查id出错，未找到该调查");
        }
        List<String> list = (List<String>) map.get("list");
        List<String> again = new ArrayList<>();
        if(list.size()>0) {
            for (String i : list) {
                User user = userRepository.findOne(i);
                SendPool sendPool = new SendPool();
                SendPool sendPool_2 = new SendPool();
                sendPool_2 = sendRepository.findByPhoneNumbrAndSurvey(user.getLongPhone(),survey.getTitle());
                if(sendPool_2!=null){
                    if(sendPool_2.getStatus().equals(Constant.INFORMING)) {
                        again.add(sendPool_2.getName());
                        continue;
                    }
                    sendPool_2.setStatus(Constant.INFORMING);
                    sendRepository.save(sendPool_2);
                }else{
                    sendPool.setSurvey(survey.getTitle());
                    sendPool.setNickName(user.getUsername());
                    sendPool.setName(user.getName());
                    sendPool.setPhoneNumbr(user.getLongPhone());
                    sendPool.setStatus(Constant.INFORMING);
                    sendPool.setNumber("0");
                    sendRepository.insert(sendPool);
                }
            }
            if(again.size()==0) {
                return Message.createSuc("成功将所选人员加入到短信池中");
            }else{
                return Message.createSuc("该调查的 "+again.toString()+"已在通知池中");
            }
        }else{
            return Message.createErr("所选人员列表为空");
        }
    }

    //获取短信池人员列表
    @GetMapping("getPool")
    public Message getPool(@RequestParam(required = false) int size,@RequestParam(required = false) int page,@RequestParam(required = false) String word){
        List<SendPool> sendPools = sendRepository.findAllByStatus(Constant.INFORMING);
        PageDatas<SendPool> pageDatas;
        if(word==null){
            pageDatas= PagingUtils.paging(page,sendPools,size);
            return Message.createSuc(pageDatas);
        }
        List<SendPool> sendPools_2;
        sendPools_2 = new ArrayList<SendPool>();
        for(SendPool sendPool:sendPools){
            if(sendPool.getName().indexOf(word)!=-1
                    ||sendPool.getNickName().indexOf(word)!=-1
                    ||sendPool.getSurvey().indexOf(word)!=-1
                    ||sendPool.getPhoneNumbr().indexOf(word)!=-1
                    ||sendPool.getNumber().indexOf(word)!=-1
                    ||sendPool.getStatus().indexOf(word)!=-1){
                sendPools_2.add(sendPool);
            }
        }
        pageDatas = PagingUtils.paging(page,sendPools_2,size);
        return Message.createSuc(pageDatas);
    }




    @PostMapping("clear")
    public Message clear(@RequestBody Map<String,List<String>> map){
        List<String> ids= map.get("ids");
        SendPool sendPool = new SendPool();
        for(String i : ids){
            sendPool = sendRepository.findOne(i);
            sendPool.setStatus(Constant.INFORMED);
            sendRepository.save(sendPool);
        }
        return Message.createSuc("所选人员已全部清空");
    }


    @PostMapping("inform")
    public Message inform_2(@RequestBody Map<String,List<String>> map){
        SendPool sendPool = new SendPool();
        List<String> ids = map.get("ids");
        List<SendPool> list = new ArrayList<>();
        Iterator<String> iterator = ids.iterator();
        while(iterator.hasNext()){
            sendPool = sendRepository.findOne(iterator.next());
            sendPool.setStatus(Constant.INFORMED);
            sendPool.setNumber((Integer.parseInt(sendPool.getNumber())+1)+"");
            sendRepository.save(sendPool);
            list.add(sendPool);
        }
        Set<SendPool> set = new HashSet<>();
        Collections.sort(list, (o1, o2) -> new Integer(o2.getNumber()).compareTo(new Integer(o1.getNumber())));
        set.addAll(list);
        List<String> newList0 = new ArrayList<>();
        List<String> newList1 = new ArrayList<>();
        Iterator<SendPool> iterator_set = set.iterator();
        while(iterator_set.hasNext()){
            sendPool = iterator_set.next();
            if(new Integer(sendPool.getNumber())>1){
                newList1.add(sendPool.getPhoneNumbr());
            }else{
                newList0.add(sendPool.getPhoneNumbr());
            }
        }
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            try {
                int i=0;
                String content_0 = "您好，您已被浙江工商大学任期目标管理工作领导小组选为测评人，请登录“ qure.zjgsu.edu.cn/ghc/answer/login.html ”填写满意度调查问卷，登录账号是您的学号/工号，登录密码是您收到短信的这个手机号。";
                //String content_1 = "我们是浙江工商大学任期目标管理工作领导小组，您有个别部门满意度调查问卷还未填写。请尽快登录“ qure.zjgsu.edu.cn/ghc/answer/login.html ”进行填写，登录账号是您的学号/工号，登录密码是您收到短信的这个手机号。";
                String content_1 = "您好，您有满意度调查问卷还未填写。请登录“ qure.zjgsu.edu.cn/ghc/answer/login.html ”填写，账号是学号/工号，密码是本手机号码，谢谢您对我们工作的大力支持。学校任期目标管理工作领导小组办公室";
                StringBuffer stringBuffer = new StringBuffer();
                if(!newList0.isEmpty()) {
                    for (String str : newList0) {
                        i++;
                        if (i == 1) {
                            stringBuffer.append(str);
                        } else {
                            stringBuffer.append("," + str);
                        }
                        if (i % 200 == 0) {
                            String value = urlService.send_2(stringBuffer.toString(), content_0);
                            logger.info("通知人数：{}",i);
                            stringBuffer = new StringBuffer();
                            i = 0;
                            TimeUnit.SECONDS.sleep(300);
                        }
                    }
                    if (stringBuffer.length() != 0) {
                        urlService.send_2(stringBuffer.toString(), content_0);
                        logger.info("通知人数：{}",i);
                    }
                }
                if(!newList1.isEmpty()) {
                    i = 0;
                    stringBuffer = new StringBuffer();
                    for (String str : newList1) {
                        i++;
                        if (i == 1) {
                            stringBuffer.append(str);
                        } else {
                            stringBuffer.append("," + str);
                        }
                        if (i % 200 == 0) {
                            String value = urlService.send_2(stringBuffer.toString(), content_1);
                            logger.info("通知人数：{}",i);
                            stringBuffer = new StringBuffer();
                            i = 0;
                            TimeUnit.SECONDS.sleep(300);

                        }
                    }
                    if (stringBuffer.length() != 0) {
                        urlService.send_2(stringBuffer.toString(), content_1);
                        logger.info("通知人数：{}",i);
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        });
        executorService.shutdown();
        return Message.createSuc("发送成功");
    }

}